import { ref } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import { Routes, useSidebarStore } from "@chulei-ui/components";
import { 个人资产, 合同, 引导页, 我的, 星域市场, 蓝图制造 } from "./Pages";
import type { SimpleRoutePath } from "@chulei-ui/components";
import type { RouteLocationRaw, Router } from "vue-router";
import type { App } from "vue";

export const pageRoutes = new Routes([
  {
    path: "/",
    meta: {},
    component: () => import("../src/pages/base/BasePage.vue"),
    children: [合同, 蓝图制造, 星域市场, 个人资产, 我的],
  },
  引导页,
]);

const router: Router = createRouter({
  history: createWebHashHistory(),
  //@ts-ignore
  routes: pageRoutes.routes,
});

router.afterEach((to) => {
  const sideBarStore = useSidebarStore();
  if (to.meta && to.meta.paths) {
    const paths: SimpleRoutePath[] = to.meta.paths as SimpleRoutePath[];
    if (paths[0].path === "/") {
      sideBarStore.addRoute(to.path);
    }
  }
});
export default router;
export const cachedRouteNames = ref<string[]>([]);
const isCache = (args: any[]) => {
  if (args.length > 1) {
    return args[args.length - 1] !== false;
  }
  return true;
};
const addCacheIfNecessary = (args: any[]) => {
  const cacheName = ROUTER_NAME_MAP.get(args[0].path);
  if (isCache(args)) {
    if (cacheName) {
      cachedRouteNames.value.push(cacheName);
    }
  } else {
    cachedRouteNames.value = [];
  }
};

export const ROUTER_NAME_MAP = new Map<string, string>();

export const plugin = {
  install(app: App) {
    const vueRouter = app.config.globalProperties.$router;
    const { push, back } = vueRouter;

    vueRouter.push = function (...args: [to: RouteLocationRaw]) {
      addCacheIfNecessary(args);
      return push.apply(vueRouter, args);
    };
    vueRouter.back = function (cache?: boolean) {
      if (!cache) {
        cachedRouteNames.value = [];
      }
      return back.apply(vueRouter, [cache]);
    };
  },
};
